﻿#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      shoo
#
# Created:     10/06/2011
# Copyright:   (c) shoo 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import urlOpener
import re
import sys
import time
import logging
import urllib
import urllib2
import cookielib
import email.utils
from django.utils import simplejson

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

logging.getLogger().setLevel(logging.DEBUG)


LOGIN_URL = "http://id.dwmail.jp/id/authn/Login"
MAIL_LIST_URL = "https://pc.dwmail.jp/pcs/Inbox.php?FRST_FG=ON&load=1"
MAIL_URL = "https://pc.dwmail.jp/pcs/Show.php?returnPage=Inbox.php&page=&folderId=inbox&sort=uid&order=desc&mailId="

# ドコモWebメールクライアント
class Dw:
    def __init__(self, user, passwd):
        self.user= user
        self.passwd= passwd
        self.opener= urlOpener.UrlOpener()
        self.cj = cookielib.CookieJar()

    # ログイン
    def login(self):
        headers = { "Content-Type":"application/x-www-form-urlencoded",
                    "Referer": "https://id.dwmail.jp/id/authn/LoginStart?Site=dwmail.jp&Success=http%3A%2F%2Fwww.dwmail.jp%2F%3Fuid%3DNULLGWDOCOMO",
                    "User-Agent":"Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 firefox/4.0.1"
                    }
        params = {  "uname":self.user,
                    "pass":self.passwd,
                    "Submit3.x":"43",
                    "Submit3.y":"17",
                    "Site":"dwmail.jp",
                    "Success":"http://www.dwmail.jp/?uid=NULLGWDOCOMO"
                    }
        params = urllib.urlencode(params)
        return self.opener.open(LOGIN_URL+"?nocache="+str(int(time.time())), headers, params)

    # メールIDの一覧を取得
    def mailListStart(self):
        headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 firefox/4.0.1"
                    }
        res = self.opener.open(MAIL_LIST_URL+"?nocache="+str(int(time.time())), headers)
        return res.content

    # メール一覧のHTMLをパース
    def parseMailList(self, html):
        r = []
        mbox = html.split("<!--/toolbar--></div>")[1]
        pattern = re.compile(r'<input type="checkbox" name="mail\[\]" id="mail\d+" value="(\d+)">',
                            re.MULTILINE | re.DOTALL)
        mails = mbox.split('<tr>')
        for mail in mails:
            if mail.find('mb_imode.gif')<0:
                # iモードメールではない
                continue
            if mail.find('ﾓｰﾄﾞ.net ﾛｸﾞｲﾝ通知ﾒｰﾙ')>=0:
                # ログイン通知メールは無視
                continue
            matcher = pattern.search(mail)
            if matcher:
                r.append(int(matcher.group(1)))
        r.sort()
        return r

    # メールを取得
    def getMail(self,id):
        headers = { "Referer": "http://pc.dwmail.jp/pcs/Inbox.php?FRST_FG=ON&load=1",
                    "User-Agent":"Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 firefox/4.0.1"
                    }
        res = self.opener.open(MAIL_URL+str(id)+"&nocache="+str(int(time.time())), headers)
        html = res.content
        return self.parseMail(html)

    # htmlからメールの内容を取り出す
    def parseMail(self, html):
    	html = unicode(html,'utf8')
    	html = html.split('<!--/toolbar-->')[1]
    	html = html.split('<!--html_mail_wrapper-->')
    	header = html[0]

    	reflag=re.MULTILINE | re.DOTALL

    	mail={}
        m = re.search(r'<dd class="subject"><a[^<>]+><span[^<>]+><img[^<>]+></span></a>\s?(.*?)</dd>', header, reflag)
    	mail['subject'] = m.group(1)

        m = re.search(r'^Date:([^<>]+)<br>',header, reflag)
        mail['date'] = email.utils.parsedate_tz(m.group(1))

    	m = re.search(r'^From:([^<>]+)<br>', header, reflag)
    	mail['from'] = [addr.strip() for addr in m.group(1).split(',')]

    	m = re.search(r'^To:([^<>]+)<br>', header, reflag)
    	if m:
    		mail['to'] = [addr.strip() for addr in m.group(1).split(',')]

    	m = re.search(r'^Cc:([^<>]+)<br>', header, reflag)
    	if m:
    		mail['cc'] = [addr.strip() for addr in m.group(1).split(',')]

    	m = re.search(r'^Bcc:([^<>]+)<br>', header, reflag)
    	if m:
    		mail['bcc'] = [addr.strip() for addr in m.group(1).split(',')]

    	index = header.find(u'<dt>添付</dt>')
    	if index>0:
    		mail['attach']=[]
    		attach = header[index:]
    		for url,name in re.findall(r'<li><a href="([^<>]+)">([^<>]+)</a>[^<>]+</li>', attach):
    			mail['attach'].append((url, name))
    	mail['body'] = html[1].split('<!--/html_mail_wrapper-->')[0]
    	return mail

def dict2str(dic):
    orig = simplejson.dumps(dic, indent=4)
    return eval("u'''%s'''" % orig).encode('utf-8')
